/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.inter.controller.api;

import cn.simastudio.talos.common.constants.ApiStatusCode;
import cn.simastudio.talos.common.constants.SimaConstants;
import cn.simastudio.talos.common.model.JsonResult;
import cn.simastudio.talos.common.utils.ExceptionUtils;
import cn.simastudio.talos.common.utils.RandomDigitsGenerator;
import cn.simastudio.talos.core.exception.system.ComponentMissingException;
import cn.simastudio.talos.inter.enums.SMSTemplate;
import cn.simastudio.talos.ucpaas.client.UCPaaSClient;
import cn.simastudio.talos.ucpaas.model.SMSResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * Usage:
 *
 * @author Charkey
 * @date 2015/7/3 11:37
 */
@RestController
@RequestMapping("/api/sms")
public class SMSApiController {

    @Autowired(required = false)
    private UCPaaSClient ucPaaSClient;

    @Autowired
    private CacheManager cacheManager;

    private Cache telCaptchaCache;

    private Cache configurationCache;

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @PostConstruct
    public void afterPropertiesSet() {
        telCaptchaCache = cacheManager.getCache("telCaptchaCache");
        configurationCache = cacheManager.getCache("configurationCache");
    }

    @RequestMapping(value = "/captcha/{tel}", method = RequestMethod.GET)
    public Object sendSMS(@PathVariable("tel") String tel) {
        // 本应用下同一号码每天可接受短信，语音验证码最大次数，配置在UCPaaS，目前配置数值为10；
        String UCPaaSCaptchaLength = configurationCache.get("UCPaaSCaptchaLength").get() + "";
        // 生成纯数字验证码，具体多少位配置在数据库中，key为UCPaaSCaptchaLength
        RandomDigitsGenerator randomDigitsGenerator = new RandomDigitsGenerator(Integer.parseInt(UCPaaSCaptchaLength));
        String captcha = randomDigitsGenerator.random();

        try {
            if (ucPaaSClient == null) {
                throw new ComponentMissingException();
            }
            SMSResponse smsResponse = ucPaaSClient.sendSMS(captcha, SimaConstants.CAPTCHA_VALID_MINUTES, tel, SMSTemplate.Capture.getInfo());
            if (smsResponse != null && SMSResponse.SUCCESS_CODE.equals(smsResponse.getRespCode())) {
                // 将手机号和验证码关联存储到缓存中，之前获取的验证码也保留，以便校验都能通过
                String oldCaptcha = telCaptchaCache.get(tel) != null ? telCaptchaCache.get(tel).get() + "" : "";
                telCaptchaCache.put(tel, oldCaptcha + "," + captcha);
                LOGGER.debug("Captcha send successfully. RespCode: {}", smsResponse.getRespCode());
                JsonResult result = new JsonResult();
                result.setCode(smsResponse.getRespCode());
                result.setMessage("Captcha send successfully");
                return result;
            } else {
                LOGGER.debug("Captcha send failed. RespCode: {1}", smsResponse != null ? smsResponse.getRespCode() : ApiStatusCode.GENERAL_EXCEPTION);
                JsonResult result = new JsonResult();
                result.setCode(smsResponse != null ? smsResponse.getRespCode() : ApiStatusCode.GENERAL_EXCEPTION);
                result.setMessage("Captcha send failed");
                return result;
            }
        } catch (IOException e) {
            JsonResult result = new JsonResult();
            result.setCode(ApiStatusCode.GENERAL_EXCEPTION);
            result.setMessage(ExceptionUtils.getExceptionMessage(e));
            return result;
        }
    }

    @RequestMapping(value = "/password/restore/{tel}", method = RequestMethod.GET)
    public Object sendSMSOfResetPassword(@PathVariable("tel") String tel) {
        // 本应用下同一号码每天可接受短信，语音验证码最大次数，配置在UCPaaS，目前配置数值为10；
        String UCPaaSCaptchaLength = configurationCache.get("UCPaaSCaptchaLength").get() + "";
        // 生成纯数字验证码，具体多少位配置在数据库中，key为UCPaaSCaptchaLength
        RandomDigitsGenerator randomDigitsGenerator = new RandomDigitsGenerator(Integer.parseInt(UCPaaSCaptchaLength));
        String captcha = randomDigitsGenerator.random();

        try {
            if (ucPaaSClient == null) {
                throw new ComponentMissingException();
            }
            SMSResponse smsResponse = ucPaaSClient.sendSMS(captcha, SimaConstants.CAPTCHA_VALID_MINUTES, tel, SMSTemplate.ResetPassword.getInfo());
            if (smsResponse != null && SMSResponse.SUCCESS_CODE.equals(smsResponse.getRespCode())) {
                // 将手机号和验证码关联存储到缓存中，之前获取的验证码也保留，以便校验都能通过
                String oldCaptcha = telCaptchaCache.get(tel) != null ? telCaptchaCache.get(tel).get() + "" : "";
                telCaptchaCache.put(tel, oldCaptcha + "," + captcha);

                JsonResult result = new JsonResult();
                result.setCode(smsResponse.getRespCode());
                result.setMessage("Captcha send successfully");
                return result;
            } else {
                JsonResult result = new JsonResult();
                result.setCode(smsResponse != null ? smsResponse.getRespCode() : ApiStatusCode.GENERAL_EXCEPTION);
                result.setMessage("Captcha send failed");
                return result;
            }
        } catch (IOException e) {
            JsonResult result = new JsonResult();
            result.setCode(ApiStatusCode.GENERAL_EXCEPTION);
            result.setMessage(ExceptionUtils.getExceptionMessage(e));
            return result;
        }
    }

}
